/**
 * function:
 * requrement:need import jquery plugins:jquery.tabpanel, jquery.magicform, jquery.jqgrid
 * @author watson  email: watson.wu@hotmail.com
 * @date 2009-9-2
 */
$.fn.MagicWork=function(opt){
	var cfg={
		table:false,//required
		url:{
			init:false,//this and data choice one
			initcallback:false,
			create:false,
			createcallback:false,
			read:false,//data?param1=value1&table=?
			readcallback:false,
			update:false,
			updatecallback:false,
			drop:false,
			dropcallback:false
		},
		data:false,
		pager:true,
		pagesize:10
	};
	opt=$.extend(true,{},cfg,opt);
	var $datagrid={};
	var $pk;
	if(!validateConf()) return false;
	_this=$(this);
	var $tabpanel=_this.TabPanel({
		items:[
			{title:'&nbsp;List&nbsp;',closed:false,icon:false,html:'<div id="mw-list" class=""/>',callback:function(){loadTableSchemal();}}
		],
		tabScroll:false,
		width:_this.width(),
		height:_this.height()-10,
		tabcontentWidth:_this.width()
	});
	
	function validateConf(){
		//TODO validation
		return true;
	};
	
	function validateData(data){
		//TODO validation
		return true;
	};
	
	function loadTableSchemal(){
		if(opt.url.init){
			$.getJSON(opt.url.init+opt.table,null,function(json){
				if(json) {
					if(!validateData(json))return false;
					opt.data=json;
					if(opt.url.initcallback)
						opt.url.initcallback();
					if(!opt.data) return false;//error
					var $data=opt.data;
					initToolBar($data);//init toolbar for CRUD 
					showdata($data);
				}
			});
		}
	};
	
	function initToolBar(data){
		var $new=$('<label class="new">New</label>').click(function(){
			//new operation
			var $id=$tabpanel.getIndex();
			var $target='<div id="mw-new-'+$id+'"/>';
			$tabpanel.addTab({title:'New-'+$id,closed:true,html:$target,callback:function(){
				$($target).MagicForm({
					url:opt.url.create+opt.table,
					callbackAfterSubmit:opt.url.createcallback,
					data:opt.data
				});
			}});
		});
		var $edit=$('<label class="edit">Edit</label>').click(function(){
			//edit operation
			var $ids=$datagrid.getGridParam('selarrrow');
			if(!$ids ||$ids.length==0){
				//show message alert select before edit
				showMessage('Please select row before edit',null);
			}
			for(var i in $ids){
				var $id=$ids[i];
				$.getJSON(opt.url.read+opt.table+'&'+$pk+'='+$id,null,function(json){
					if(json){
						for(var i in json.rows){
							var $data=$.extend(true,{},opt.data);
							if(typeof json.rows[i].cell=='object'){
								for(var j in $data){
									if(json.rows[i].cell[j]!='null')
										$data[j].value=json.rows[i].cell[j];
								}
							}
							var $panelId=$tabpanel.getIndex();
							var $target='<div id="mw-edit-'+$panelId+'"/>';
							$tabpanel.addTab({title:'Edit-'+$id,closed:true,html:$target,callback:function(){
								$($target).MagicForm({
									edit:true,
									url:opt.url.update+opt.table,
									callbackAfterSubmit:opt.url.updatecallback,
									data:$data
								});
							}});
						}
					}
				});
			}
		});
		var $del=$('<label class="del">Del</label>').click(function(){
			//delete operation
			var $ids=$('#mw-datagrid').getGridParam('selarrrow'); 
			if($ids){
				$drop=opt.url.drop+opt.table+"&ids="
				for(var i in $ids){
					$drop+=$ids[i]+',';
					$('#mw-datagrid').delRowData($ids[i]);
				}
				$.post($drop,{},opt.url.dropcallback?opt.url.dropcallback:false);
			}
		});
		var $query=$('<div id="query"/>');
		$('<div id="editor-toolbar"/>').append($('<div id="editor-bts">').append($new).append($edit).append($del)).append($query).appendTo($('#mw-list'));
		var $conditions=[];
		for(var i in data){
			if(data[i].attrs.searchable){
				$conditions.push(data[i]);
			}
		}
		$query.MagicForm({
			edit:'query',
			url:opt.url.read+opt.table,
			listyle:'li-inline',
			data:$conditions
		});
	};
	
	function showdata(data){
		var gridimgpath = 'images/jqgrid/images';
		$datagrid=$('<table id="mw-datagrid" class="scroll" cellpadding="0" cellspacing="0"/>');
		$('#mw-list').append($datagrid).append('<div id="mw-pager" class="scroll" style="text-align:center;"/>');
		var $colNames=[];//getColumns displayed in table header
		var $colModel=[];//getColumns map to database column with
		var $length=data.length==0?100:$('#mw-list').width()*0.99/data.length;
		for(var i in data){
			if(data[i].attrs.displayable){
				$colModel.push({name:data[i].name, index:data[i].name, width:(data[i].attrs.width?data[i].attrs.width:$length)});
				$colNames.push(data[i].attrs.label?data[i].attrs.label:data[i].name);
				if(data[i].attrs.pk)
					$pk=data[i].name;
			}
		}
		jQuery(document).ready(function(){
			$datagrid.jqGrid({ url:opt.url.read+opt.table, datatype: "json", colNames:$colNames, colModel:$colModel, rowNum:opt.pagesize, imgpath: gridimgpath, pager: (opt.pager?$('#mw-pager'):false), sortname: $pk, multiselect: true, viewrecords: true, sortorder: "desc"});
		});
	};
};